package cn.liulin.java8.lambda;

import cn.liulin.java8.pojo.Apple;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * cn.liulin.java8.lambda$
 * 复合lambda表达式方法
 * @author ll
 * @date 2021-09-17 15:26:14
 **/
public class ComplexLambdaUse {
    public static void main(String[] args) {
        thenComplex();
        predicateComplex();
        functionComplex();
    }

    /**
     * 函数复合
     * andThen 先执行f，再执行g
     * compose 先执行g，再执行f
     * @author ll
     * @date 2021-09-17 17:08:05
     * @return void
     **/
    private static void functionComplex() {
        Function<Integer, Integer> f = x -> x + 1;
        Function<Integer, Integer> g = x -> x * 2;
        Function<Integer, Integer> h = f.andThen(g);
        int result = h.apply(1);
        System.out.println(result);
        Function<Integer, Integer> i = f.compose(g);
        int result2 = i.apply(1);
        System.out.println(result2);
    }

    /**
     * 谓词复合
     * and or 优先级从左到右
     * @author ll
     * @date 2021-09-17 16:53:17
     * @return void
     **/
    private static void predicateComplex() {
        Predicate<Apple> redApple = (Apple a) -> "red".equals(a.getColor());
        Predicate<Apple> noRedApple = redApple.negate();
        Predicate<Apple> redAndHeavyApple = redApple.and(a -> a.getWeight() > 150);
        Predicate<Apple> redAndHeavyAppleOrGreen = redApple.and(a -> a.getWeight() > 150)
                .or(a -> "green".equals(a.getColor()));
    }

    /**
     * thenComplex使用
     * @author ll
     * @date 2021-09-17 16:53:10
     * @return void
     **/
    private static void thenComplex() {
        Comparator<Apple> comparing1 = Comparator.comparing(Apple::getWeight);
        Comparator<Apple> comparing2 = Comparator.comparing(Apple::getWeight).reversed();
        List<Apple> list = new ArrayList<>();
        list.sort(Comparator.comparing(Apple::getWeight)
                .reversed()
                .thenComparing(Apple::getCountry));
    }
}
